package com.nulldev.util.io.lzma;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.LinkedList;

import com.nulldev.util.io.FileUtil;
import com.nulldev.util.io.IOUtils;
import com.nulldev.util.io.lzma.lzma.Decoder;
import com.nulldev.util.io.lzma.lzma.Encoder;
import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.other.ByteUtils;

public class LZMA {

	public static byte[] compress(final byte[] data) {
		try {
			final ByteArrayOutputStream baos = new ByteArrayOutputStream();
			final LZMAOutputStream lzmao = new LZMAOutputStream(baos, new Encoder());
			lzmao.write(data);
			lzmao.close();
			final byte[] output = baos.toByteArray();
			return output;
		}catch (Exception e) {
			e.printStackTrace();
			return data;
		}
 	}
	
	public static byte[] decompress(final byte[] data0) {
		try {
			final ByteArrayInputStream bais = new ByteArrayInputStream(data0);
			final LZMAInputStream lzima = new LZMAInputStream(bais, new Decoder());	
			final LinkedList<Byte> data = new LinkedList<Byte>();
			int pos = 0;
			int read;
			while ((read = lzima.read()) != -1) {
				if (read == 31) {
					break;
				}
				data.add((byte) read);
				pos += 1;
			}
			return ByteUtils.fromList(data);
		}catch (Exception e) {
			e.printStackTrace();
			return data0;
		}
	}
}
